<template>
  <div class="divBox">
    <el-card class="box-card">
      <el-form inline size="small" @submit.native.prevent>

        <el-form-item label="租赁合同状态:">
          <el-select v-model="listPram.status" placeholder="全部" style="width: 150px">
            <el-option
                v-for="item in houseStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房屋类型:">
          <el-select v-model="listPram.houseType" placeholder="全部" style="width: 150px">
            <el-option
                v-for="item in houseTypeOptions"
                :key="item.value"
                :label="item.houseTypeName"
                :value="item.houseTypeName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属房屋:">
          <el-input v-model="listPram.fwkeyword" placeholder="请输入租赁证编号、地址关键词" clearable style="width: 250px"/>
        </el-form-item>
        <el-form-item label="承租人:">
          <el-input v-model="listPram.yhkeyword" placeholder="姓名、身份证号、手机号关键词" clearable style="width: 250px"/>
        </el-form-item>
        <el-form-item label="合同编号关键词:">
          <el-input v-model="listPram.contractNumber" placeholder="请输入租赁合同编号关键词" clearable style="width: 250px"/>
        </el-form-item>

        <el-form-item>
          <el-button icon="el-icon-search" size="mini" type="primary" @click.native="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item class="el-form-item-align-right">
          <el-button
              icon="el-icon-upload2"
              @click="handleExport('multi')"
              type="primary" size="mini" v-has-permi="['admin:house:information:export']">
            批量导出
          </el-button>
        </el-form-item>
        <el-form-item class="el-form-item-align-right">
          <el-button icon="el-icon-upload2" size="mini" type="primary" v-has-permi="['admin:house:information:import']">批量导入
          </el-button>
        </el-form-item>
        <el-form-item class="el-form-item-align-right">
          <router-link :to=" { path:'/leaseInformation/effective/edit/' } ">
            <el-button icon="el-icon-edit" size="mini" type="primary"
                       v-has-permi="['admin:leaseInformation:effective:save']">新增
            </el-button>
          </router-link>
        </el-form-item>

      </el-form>
      <el-table :data="listData.items" size="small"
                :header-cell-style=" {fontWeight:'bold',background:'#f8f8f9',color: '#515a6e',height:'40px'}" border
                @selection-change="handleSelectionChange">
        <el-table-column type="expand" align="center" width="40">
          <template slot-scope="props">
            <el-row class="house-info-row">
              <span class="info-item">
                <span class="info-label">所属房屋：</span>
                <span class="info-value">{{ props.row.houseType ||'-'}}</span>
              </span>
              <span class="info-item">
                  <span class="info-label">地段：</span>
                  <span class="info-value">{{ props.row.houseAreaType  ||'-'}}</span>
              </span>
              <span class="info-item">
                  <span class="info-label">楼层：</span>
                  <span class="info-value">
                    {{ props.row.floorLevel ||'-'}}</span>
              </span>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column align="center"
                         type="selection"
                         width="50">
        </el-table-column>
        <el-table-column align="center" label="ID" prop="id" width="40"></el-table-column>
        <el-table-column align="center" label="租赁合同编号" prop="contractNumber" width="130"/>
        <el-table-column align="center" label="关联房屋" prop="houseType" min-width="160">
          <template slot-scope="scope">
                <span @click="handleHouse(scope.row.idValue)" class="clickable-link">
                  {{ scope.row.leaseCertificateNumber }}-{{ scope.row.areaName }}{{ scope.row.streetName }}-{{ scope.row.mphValue }}
                </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="关联承租人" prop="currentTenantName" width="70">
          <template slot-scope="scope">
              <span :style="{
                border: scope.row.isArrearage === 1 ? '2px solid #ff4949' : 'none',
                padding: '2px',
                display: 'inline-block'
              }">
                {{ scope.row.currentTenantName }}
              </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="合同租赁周期" prop="timePercentage" width="250">
          <template slot-scope="scope">
            <span>剩余时长：{{ scope.row.remainingDays }}</span>
            <el-progress
                :percentage="scope.row.timePercentage"
                :color="scope.row.remainingDays < 60 ? '#F56C6C' : ''"
            ></el-progress>
          </template>
        </el-table-column>
        <el-table-column label="收费标准" header-align="center">
          <el-table-column align="center" label="应交" prop="unitPricePerSquare" width="60"/>
          <el-table-column align="center" label="实收(调差后)" prop="calculatedPrice" width="60"/>
        </el-table-column>
        <el-table-column align="center" label="建筑面积/使用面积(㎡)"  width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.buildingArea }}/{{ scope.row.usableArea }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="月租金" prop="totalPrice" width="70">
          <template slot-scope="scope" >
              <span @click="showFormula(scope.row)" class="clickable-link">
                ￥{{ scope.row.totalPrice || 0}}
              </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="租赁合同状态" prop="status" width="70">
          <template slot-scope="scope">
              <span :style="getStatusStyle(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="关联附件" prop="contractAddress" width="70">
          <template slot-scope="scope">
            <span @click="handlePreview(scope.row.contractAddress)" class="clickable-link">查看</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="470" fixed="right">
          <template slot-scope="scope">
            <el-button icon="el-icon-edit" size="mini" type="primary"
                       v-if="scope.row.status === 1 ||  scope.row.status === 4"
                       @click="openExamine(scope.row)"
                       v-has-permi="['admin:leaseInformation:effective:examine']">审核
            </el-button>
            <el-button icon="el-icon-edit" size="mini" type="primary" @click="openRenewDialog(scope.row)"
                       v-has-permi="['admin:leaseInformation:effective:renew']">发起续租
            </el-button>
            <router-link :to=" { path:'/leaseInformation/effective/edit/' + scope.row.id }">
              <el-button icon="el-icon-edit" size="mini" type="primary" style="margin-left: 10px"
                         v-has-permi="['admin:leaseInformation:effective:save']">编辑
              </el-button>
            </router-link>
            <router-link :to=" { path:'/leaseInformation/effective/edit/' + scope.row.id + '/1'}">
              <el-button icon="el-icon-edit" size="mini" type="primary" style="margin-left: 10px"
                         v-has-permi="['admin:leaseInformation:effective:detail']">详情
              </el-button>
            </router-link>
            <el-button icon="el-icon-delete" size="mini" type="danger" @click="handlerDelete(scope.row.id)" style="margin-left: 10px"
                       v-has-permi="['admin:leaseInformation:effective:delete']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          :current-page="listPram.page"
          :page-sizes="[10,20,40,60,80,100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="listData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 审核弹窗 -->
    <el-dialog
        title="审核信息"
        :visible.sync="dialogVisible"
        width="50%"
    >
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="审核状态">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">待审核</el-radio>
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="4">争议处理中</el-radio>
            <el-radio :label="5">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="auditForm.operator" disabled></el-input>
        </el-form-item>
        <el-form-item label="备注说明">
          <el-input
              type="textarea"
              v-model="auditForm.remarks"
              placeholder="请输入审核意见"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交</el-button>
      </div>
    </el-dialog>


    <!-- 续租合同弹窗 -->
    <el-dialog
        title="续租合同信息"
        :visible.sync="renewDialogVisible"
        width="60%"
        :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="合同编号">{{ contractForm.contractNo }}</el-descriptions-item>
        <el-descriptions-item label="租客姓名">{{ contractForm.tenantName }}</el-descriptions-item>
        <el-descriptions-item label="房屋地址">{{ contractForm.houseAddress }}</el-descriptions-item>
        <el-descriptions-item label="当前租金">{{ contractForm.currentRent }} 元/月</el-descriptions-item>
        <el-descriptions-item label="租赁期限">
          {{ contractForm.startDate }} 至 {{ contractForm.endDate }}
        </el-descriptions-item>
        <el-descriptions-item label="续租期限">
          <el-date-picker
              v-model="contractForm.renewPeriod"
              type="monthrange"
              range-separator="至"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
          ></el-date-picker>
        </el-descriptions-item>
        <el-descriptions-item label="续租租金">
          <el-input-number
              v-model="contractForm.renewRent"
              :min="contractForm.currentRent"
              :step="100"
              controls-position="right"
          ></el-input-number> 元/月
        </el-descriptions-item>
        <el-descriptions-item label="备注说明" :span="2">
          <el-input
              type="textarea"
              v-model="contractForm.remarks"
              placeholder="请输入续租特殊条款"
          ></el-input>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer">
        <el-button @click="renewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRenew">确认续租</el-button>
      </div>
    </el-dialog>

    <el-dialog title="月租金计算公式" :visible.sync="dialogVisible2" width="50%">
      <div>
        <p><strong>计算公式：</strong>应交月租金 = 使用面积 x 调差后收费标准</p>
        <div v-if="currentRow2">
          <p style="margin-top: 10px;margin-left: 145px"  > =
            {{currentRow2.usableArea || 0}} x {{currentRow2.calculatedPrice || 0}} = ￥{{currentRow2.totalPrice || 0}}
          </p>
        </div>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import {getAdminGetFwlx } from "@/api/house";
import {examineFwRenewalRecord, list,deleteRow} from "@/api/leaseInformation";
import {checkPermi} from "@/utils/permission";
import {exportMultiColumn} from "@/api/export";

export default {
  data() {
    return {
      listData: {
        items: [], total: 0
      },
      listPram: {
        page: 1,
        limit: 10,
        contractNumber: '',
        status: '',
        fwkeyword: '',
        houseType: '',
        yhkeyword: '',
      },
      editDialog: {
        visible: false,
        isCreate: 0, // 0=创建，1=编辑
        editDate: {},
      },
      tableLoading: false,
      houseTypeOptions: [],
      houseStatusOptions: [{
        value: '1',
        label: '待审核'
      }, {
        value: '2',
        label: '生效中'
      }, {
        value: '3',
        label: '已终止'
      }, {
        value: '4',
        label: '争议处理中'
      }],
      multipleSelection: [],
      dialogVisible: false, // 控制弹窗显示
      auditForm: {
        status: 1,       // 审核状态： 1待审核、2生效中、3已终止、4争议处理中、5审核拒绝
        operator: '',    // 操作人（从全局状态或接口获取）
        remarks: ''      // 备注
      },
      currentRow: null,   // 当前操作的行数据

      renewDialogVisible: false, // 控制弹窗显示
      contractForm: {
        contractNo: '',
        tenantName: '',
        houseAddress: '',
        currentRent: 0,
        startDate: '',
        endDate: '',
        renewPeriod: [], // 续租时间范围
        renewRent: 0,    // 续租租金
        remarks: ''
      },
      dialogVisible2: false,
      currentRow2: null,

    }
  },
  mounted() {
    this.imageUrl = process.env.VUE_APP_IMAGE_URL
    this.getList()
    this.getHouseType()
  },
  methods: {
    checkPermi,
    getList() {
      this.tableLoading = true
      list(this.listPram).then(res => {
        this.listData = res;
        this.listData.items.forEach(item => {
          item.fileUrl= 'https://example.com/contract.pdf'
        })
      }).finally(() => {
        this.tableLoading = false;
      })

    },
    handleSearch() {
      this.listPram.page = 1;
      this.getList();
    },
    getHouseType() {
      // 获取房屋类型
      getAdminGetFwlx().then((res) => {
        this.houseTypeOptions = res
      })
    },
    // 显示弹窗
    showFormula (row) {
      this.currentRow2 = row;
      this.dialogVisible2 = true;
    },
    openEdit(isCreate, editDate) {
      this.editDialog.editDate = editDate;
      this.editDialog.isCreate = isCreate;
      this.editDialog.visible = true
    },
    handlerDelete(id) {
      this.$confirm('确认删除该数据吗？').then(() => {
        const loading = this.$loading({text: '删除中', background: 'rgba(255,255,255,.5)'})
        deleteRow({id:id}).then(() => {
          this.$message.success('删除成功')
          this.getList()
        }).finally(() => {
          loading.close()
        })
      })
    },
    handleExport(){
      exportMultiColumn().then(() => {
      }).finally(() => {
      })
    },
    hideEditDialog() {
      this.editDialog.visible = false
      this.getList()
    },
    handleSizeChange(val) {
      this.listPram.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listPram.page = val
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    resetQuery() {
      this.listPram.contractNumber = '';
      this.listPram.status = '';
      this.listPram.fwkeyword = '';
      this.listPram.houseType = '';
      this.listPram.yhkeyword = '';
      this.listPram.page = 1;
      this.getList()
    },
    handleHouse(currentHouse) {
      this.$router.push({
        path: '/house/information',
        query: {
          currentHouse: currentHouse // 携带当前承租人名称作为查询参数
        }
      });
    },
    handlePreview(url) {
      // 假设url为PDF文件
      window.open(url, '_blank');
    },
    getStatusStyle(status) {
      switch (status) {
        case 1: return { color: '#e6a23c' } // 待审核 - yellow
        case 2: return { color: '#f56c6c' } // 生效中 - red
        case 3: return { color: '#409eff' } // 已终止 - blue
        case 4: return { color: '#f56c6c' } // 争议处理中 - red
        default: return {}
      }
    },
    getStatusText(status) {
      const statusMap = {
        1: '待审核',
        2: '生效中',
        3: '已终止',
        4: '争议处理中'
      }
      return statusMap[status] || '未知状态'
    },
    // 打开弹窗并初始化数据
    openExamine(row) {
      this.currentRow = row;
      // this.auditForm.operator = this.$store.state.user.name; // 假设操作人从Vuex获取
      this.dialogVisible = true;
    },
    // 提交审核
    async submitAudit() {
      try {
        const params = {
          id: this.currentRow.id,
          status: this.auditForm.status,
          remarks: this.auditForm.remarks
        };
        this.tableLoading = true
        examineFwRenewalRecord(params).then(() => {
          this.$message.success('审核成功');
          this.dialogVisible = false;
          this.getList();
          this.$emit('refresh'); // 通知父组件刷新数据
        }).finally(() => {
          this.tableLoading = false;
        })
      } catch (error) {
        this.$message.error('审核失败');
      }
    },

    // 打开续租弹窗并加载合同数据
    openRenewDialog(row) {
      this.renewDialogVisible = true;
      // 从行数据初始化合同信息（模拟API调用）
      this.loadContractData(row.id).then(res => {
        this.contractForm = {
          ...res.data,
          renewRent: res.data.currentRent, // 默认续租租金=当前租金
          renewPeriod: [] // 清空续租期限选择
        };
      });
    },
    // 模拟获取合同详情API
    async loadContractData() {
      return {
        data: {
          contractNo: 'HT20250001',
          tenantName: '张三',
          houseAddress: '北京市朝阳区XX小区5栋302',
          currentRent: 5000,
          startDate: '2025-01-01',
          endDate: '2025-12-31'
        }
      };
    },
    // 提交续租申请
    submitRenew() {
      if (!this.contractForm.renewPeriod || this.contractForm.renewPeriod.length !== 2) {
        this.$message.error('请选择完整的续租期限');
        return;
      }
      const params = {
        contractId: this.contractForm.contractNo,
        newStartDate: this.contractForm.renewPeriod[0],
        newEndDate: this.contractForm.renewPeriod[1],
        newRent: this.contractForm.renewRent,
        remarks: this.contractForm.remarks
      };
      this.$api.contract.renew(params).then(() => {
        this.$message.success('续租申请已提交');
        this.renewDialogVisible = false;
        this.$emit('refresh'); // 通知父组件刷新表格数据
      });
    }

  }
}
</script>

<style scoped lang="scss">
::v-deep .el-checkbox__inner {
  border-color: #1879fe;
}
.clickable-link {
  color: #1890ff;
  cursor: pointer;
  text-decoration: none;
}

.clickable-link:hover {
  text-decoration: underline;
  color: #1890ff;
}
.house-info-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px; /* 调整项与项之间的间距 */
  margin: 8px 0;
  font-size: 14px;
}
.info-item {
  display: inline-flex;
  align-items: center;
  margin-left: 50px;
}

.info-label {
  color: #909399; /* ElementUI的次要文字颜色 */
  margin-right: 4px;
}

.info-value {
  color: #606266; /* ElementUI的主要文字颜色 */
}
</style>
